import 'dart:convert';

import 'package:dio/dio.dart' as dio;
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:get/get.dart';
import '../../global/user/logic.dart';
import '../logutil.dart';
import '../util.dart';
import 'resultdata.dart';

/// 数据初步处理
class ResponseInterceptors extends InterceptorsWrapper {
  @override
  void onResponse(
      dio.Response response, dio.ResponseInterceptorHandler handler) {
    if (EasyLoading.isShow) {
      EasyLoading.dismiss();
    }

    RequestOptions option = response.requestOptions;

    try {
      if (option.contentType != null && option.contentType!.contains("text")) {
        response.data = ResultData(response.data, true, 200);
        handler.next(response);
      }

      //一般只需要处理200的情况，300、400、500保留错误信息，外层为http协议定义的响应码
      if (response.statusCode == 200 || response.statusCode == 201) {
        //内层需要根据公司实际返回结构解析，一般会有code，data，msg字段
        // LogUtil.d(jsonEncode(response.data));
        Get.log(jsonEncode(response.data));

        int status = response.data["status"];
        // if (status == null) {
        //   status = response.data['code'];
        // }

        if (status == 200 || status == 0) {
          response.data = ResultData(response.data['data'], true, 200,
              headers: response.headers);
          handler.next(response);
        } else if (status == 401) {
          // EasyLoading.showToast('登录过期，请重新登录。');
          UserController.instance.loginOutSuccess();
          Get.offAllNamed(RouterPath.login);
        } else {
          // EasyLoading.showToast(response.data["message"].toString());
          // response.data = ResultData(response.data, false, 200,
          //     headers: response.headers,message: response.data["message"]);
          // handler.next(response);
          EasyLoading.showToast(response.data['message'].toString());
          response.data = ResultData(response.data, false, status);
          handler.next(response);
        }
      }
    } catch (e) {
      print("ResponseError====" + e.toString() + "****" + option.path);

      response.data = ResultData(response.data, true, response.statusCode!,
          headers: response.headers);
      handler.next(response);
    }

    // response.data = ResultData(response.data, false, response.statusCode!, headers: response.headers);
    // handler.next(response);
  }
}
